<?php

namespace App\Admin\Controllers;

use App\Models\Category;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class CategoryController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Category(), function (Grid $grid) {
//            $grid->tools('<a class="btn btn-primary disable-outline">测试按钮</a>');
            $grid->model()->orderBy('id', 'desc');
            // 禁用过滤器按钮
            $grid->disableFilterButton();
            $grid->column('id','序号')->sortable();
            $grid->column('name','类别名称');
//            $grid->column('icon','图标');
            $grid->column('created_at','添加时间');
            $grid->column('updated_at','更新时间')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Category(), function (Show $show) {
            $show->field('id','序号');
            $show->field('name','类别名称');
//            $show->field('icon','图标');
            $show->field('created_at','添加时间');
            $show->field('updated_at','更新时间');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Category(), function (Form $form) {

            $form->submitted(function (Form $form) {
                $name = $form->name;
                if ($form->isCreating()) {
                    if (Category::where('name',$name)->exists()) {
                        $form->responseValidationMessages('name', '此类别名称已经存在了，换个一个名字吧');
                    }
                } elseif ($form->isEditing()) {
                    if (Category::where('name',$name)->where('id', '!=', $form->model()->id)->exists()) {
                        $form->responseValidationMessages('name', '此类别名称已经存在了，换个一个名字吧');
                    }
                }
            });

            $form->display('id','序号');
            $form->text('name','类别名称')->required();
            $form->display('created_at','添加时间');
            $form->display('updated_at','更新时间');

            $form->disableEditingCheck();
            $form->disableCreatingCheck();
            $form->disableViewCheck();
            $form->disableResetButton();
        });
    }
}
